package com.luo.demo.multi.ds.dynamic.tenant;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.luo.demo.multi.ds.dynamic.utils.HttpContextUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 租户处理器
 *
 * @author luohq
 * @date 2022-08-07 12:31
 */
@Slf4j
public class MyTenantLineHandlerImpl implements TenantLineHandler {
    /**
     * 租户ID请求头名称
     */
    public static final String TENANT_ID_HEADER = "X-TENANT-ID";
    /**
     * 默认租户ID
     */
    public static final Long DEFAULT_TENANT_ID = 1L;
    /**
     * 不进行租户处理的table
     */
    private static final List<String> IGNORE_TABLES = Arrays.asList("my_tenant");

    @Override
    public Expression getTenantId() {
        Long tenantId = Optional.ofNullable(HttpContextUtils.getRequestHeader(TENANT_ID_HEADER))
                .map(Long::valueOf)
                //.orElseThrow(() -> new RuntimeException("解析请求头中的X—TENANT-ID失败！"));
                .orElseGet(() -> {
                    log.info("解析请求头中的X-TENANT-ID失败 - 使用默认租户ID: {}", DEFAULT_TENANT_ID);
                    return DEFAULT_TENANT_ID;
                });
        return new LongValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        //默认tenant_id
        return "tenant_id";
    }

    @Override
    public boolean ignoreTable(String tableName) {
        //是否忽略此table的租户处理逻辑
        return IGNORE_TABLES.contains(tableName);
    }
}
